package com.example.controller;

import com.example.entity.Order;
import com.example.listener.PayListener;
import com.example.service.OrderService;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * datetime : 2020/10/7 8:12
 * author : shenxiang
 */
@Controller
@RequestMapping("/order")
public class IndexController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PayListener payListener;

    @RequestMapping("/")
    public ModelAndView index(ModelAndView model){
        model.setViewName("index");
        return model;
    }

    @RequestMapping("/create_order")
    public ModelAndView createOrder(ModelAndView model, HttpServletRequest request) throws UnsupportedEncodingException {
        // 写入消息队列,写入数据库
        String orderNo = "202010070814000001";
        MessageProperties messageProperties = MessagePropertiesBuilder.newInstance().setContentEncoding("utf-8").build();
        Message message = MessageBuilder.withBody(orderNo.getBytes("utf-8")).andProperties(messageProperties).build();
        rabbitTemplate.send("ex.pay.biz","key.pay.biz",message);

        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setOrderAmount(73.0);
        order.setOrderDescription("G88 19:55-20:50 杭州东到上海虹桥火车票一张");
        order.setOrderStatus(0);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        orderService.save(order);

        model.setViewName("create_order");
        return model;
    }

    @RequestMapping("/pay")
    public ModelAndView pay(ModelAndView model) throws UnsupportedEncodingException {
        // 消费消息队列中的待支付消息,如果查库发现已经是取消状态则告知订单已经被取消
        Message message = rabbitTemplate.receive("queue.pay.biz");
        if (message != null){
            String orderNo = new String(message.getBody(),message.getMessageProperties().getContentEncoding());
            // 将表中的订单号修改为已支付,更新时间
            orderService.setPayedByOrderNo(orderNo);
            System.out.println("将订单设置为支付成功成功");
            model.setViewName("pay");
        }else{
            System.out.println("订单已经超时被自动取消,请重新下单");
            model.setViewName("canceled");
        }
        return model;
    }

    @RequestMapping("/getAll")
    @ResponseBody
    public List<Order> getAll(){
        return orderService.getAll();
    }
}
